import { DownOutlined, UpOutlined } from '@ant-design/icons';
import { Button, Form, FormInstance, Input, Select } from 'antd';
import classNames from 'classnames';
import { ComponentProps, forwardRef, useImperativeHandle, useState } from 'react';

import classes from './index.module.scss';
type Props = {
  fields: FieldItem[];
  cols?: number;
  initParams?: Record<string, any>;
  onSearch?: (params: Record<string, any>) => void;
  onReset?: () => void;
};

const widgets = {
  input: Input,
  select: Select,
} as const;

// 展开为联合类型
type FieldItem = {
  label: string;
  prop: string;
} & {
  [K in keyof typeof widgets]: { widget: K; props?: ComponentProps<(typeof widgets)[K]> };
}[keyof typeof widgets];

export type TableSearchRef = FormInstance<any>;

const TableSearch = forwardRef(
  ({ fields, cols = 3, initParams = {}, onSearch = () => {}, onReset = () => {} }: Props, ref) => {
    const [showAll, setShowAll] = useState(false);
    const [form] = Form.useForm();

    useImperativeHandle(ref, () => form, [form]);

    return (
      <Form form={form} initialValues={initParams}>
        {fields.map((field, i) => {
          const w = field.widget || 'input';
          const Widget = widgets[w] as any;
          const props = field.props || {};
          return (
            <div className={classNames(classes.item, !showAll && i >= cols - 1 && classes.hide)} key={field.prop}>
              <Form.Item label={field.label} name={field.prop}>
                <Widget {...props} />
              </Form.Item>
            </div>
          );
        })}
        <div className={classNames(classes.item, classes.btns, showAll && classes.all)}>
          <Button
            onClick={() => {
              form.resetFields();
              onReset();
            }}
          >
            重置
          </Button>
          <Button type="primary" onClick={() => onSearch(form.getFieldsValue())}>
            查询
          </Button>
          {fields.length > cols - 1 && (
            <Button
              className={classes.icon}
              onClick={() => setShowAll(!showAll)}
              icon={showAll ? <UpOutlined /> : <DownOutlined />}
            ></Button>
          )}
        </div>
      </Form>
    );
  }
);

export default TableSearch;
